package com.mooc.yohoshop.dao;

import org.greenrobot.greendao.query.WhereCondition;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public abstract class DaoCRUDImpl<T>{
    private Class clazz;
    public DaoCRUDImpl(){
        ParameterizedType type = (ParameterizedType)
                getClass().getGenericSuperclass();
        clazz = (Class) type.getActualTypeArguments()[0];
    }
    public boolean insert(T t){
        if (t == null)
            return false;
        return DaoDBUtils.getInstance().getDaoSession().insert(t)>0;
    }
    public boolean inserts(List<T>datas){
        if (datas == null)
            return false;
        if (datas.size() == 0)
            return false;
        boolean flag = true;
        for (T t : datas){
            flag = insert(t);
        }
        return flag;
    }

    public List<T> selectAll(){
        return DaoDBUtils.getInstance().getDaoSession().queryBuilder(clazz).list();
    }

    public T select(WhereCondition whereCondition){
        return (T) DaoDBUtils.getInstance().getDaoSession().queryBuilder(clazz)
                .where(whereCondition).unique();
    }
    public boolean update(T t){
        return DaoDBUtils.getInstance().getDaoSession().insertOrReplace(t) > 0;
    }
    public boolean updateAll(List<T>datas){
        boolean flag = true;
        for (T t:datas)
            flag = update(t);
        return flag;
    }
    public void delete(T t){
        DaoDBUtils.getInstance().getDaoSession().delete(t);
    }

    public void deleteAll(){
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Type[] types = type.getActualTypeArguments();
        DaoDBUtils.getInstance().getDaoSession().deleteAll(types[0].getClass());
    }

}
